import 'package:flutter/material.dart';
// import 'package:pandabuy/r.dart';

/// 模式1：给value参数，不保持状态，由父组件指定开关状态；
/// 模式2：不给value参数，自己记忆开关状态；
class PandaSwitch extends StatefulWidget {
  const PandaSwitch({
    Key? key,
    this.initialValue,
    this.value,
    this.onChanged,
    this.width,
    this.height,
    this.margin,
    this.padding,
  }) : super(key: key);

  final bool? initialValue;
  final bool? value;
  final void Function(bool)? onChanged;
  final double? width;
  final double? height;
  final EdgeInsetsGeometry? margin;
  final EdgeInsetsGeometry? padding;

  @override
  State<PandaSwitch> createState() => _PandaSwitchState();
}

class _PandaSwitchState extends State<PandaSwitch> {
  late bool _isOn;

  @override
  void initState() {
    super.initState();

    /// 初始值由外部指定；不指定的话，给默认值false
    _isOn = widget.initialValue ?? false;
  }

  @override
  Widget build(BuildContext context) {
    /// 如果外部指定了值，那么强制设定为外部值
    if (widget.value != null) {
      _isOn = widget.value!;
    }

    var imageName = _isOn ? 'assets/imgs/ic_switch_on.png' : 'assets/imgs/ic_switch_off.png';
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          _isOn = !_isOn;
        });
        if (widget.onChanged != null) {
          widget.onChanged!(_isOn);
        }
      },
      child: Container(
        color: Colors.transparent,
        width: widget.width,
        height: widget.height,
        margin: widget.margin,
        padding: widget.padding,
        child: Center(
          child: Image.asset(imageName),
        ),
      ),
    );
  }
}